const mysql = require('mysql');
const config = require('./../../config');

module.exports = {

  defaultQueryParameter: {
    sort: 'crdt',
    direction: 'asc',
    page: 1,
    size: 5
  },

  mergeObject (obj) {
    if (typeof obj !== 'object') {
      return obj;
    }
    let params = Array.prototype.slice.call(arguments, 1);
    params.forEach(function (param) {
      if (typeof param === 'object') {
        for (let prop in param) {
          obj[prop] = param[prop];
        }
      }
    });
    return obj
  },

  executeSql (sql) {
    return new Promise((resolve, reject) => {
      let connection = mysql.createConnection(config.db);
      connection.connect();
      connection.query(sql, (error, results) => {
        if (error) {
          reject(error);
        }
        resolve(results);
      });
      connection.end();
    });
  },

  generateUUID (length = 24) {
    let str = `abcdedfghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890`;
    let rs = '';
    let rnd = 0;
    let len = str.length;
    for (let i = 0; i < length; i++) {
      rnd = Number.parseInt(Math.random() * len);
      rs += str[rnd];
    }
    return rs;
  }
};